package com.zzyy.study.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyy.study.config.RabbitMQConfiguration;
import com.zzyy.study.entities.CreateOrderRequest;
import com.zzyy.study.entities.OrderPO;
import com.zzyy.study.mapper.OrderMapper;
import com.zzyy.study.mq.sender.IMsgSender;
import com.zzyy.study.service.IOrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.concurrent.TimeUnit;
/**
 * @auther zzyy
 * @create 2024-07-14 15:49
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implements IOrderService
{
    @Resource
    private IMsgSender msgSender;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createOrder(CreateOrderRequest req)
    {
        OrderPO orderPO = new OrderPO();
        orderPO.setId(IdUtil.fastSimpleUUID());
        orderPO.setGoods(req.getGoods());
        orderPO.setPrice(req.getPrice());
        this.save(orderPO);

        log.info("投递订单消息");

        if (req.getDelaySeconds() == 0) {
            //（立即投递）
            log.info("***立即投递，消息：{}", orderPO);
            this.msgSender.sendWithBody(RabbitMQConfiguration.Order.EXCHANGE, RabbitMQConfiguration.Order.ROUTING_KEY, orderPO);
        } else {
            //（延迟投递）
            log.info("***延迟投递，消息：{}", orderPO);
            this.msgSender.sendWithBody(RabbitMQConfiguration.Order.EXCHANGE, RabbitMQConfiguration.Order.ROUTING_KEY, req.getDelaySeconds(), TimeUnit.SECONDS, orderPO);
        }

        return orderPO.getId();
    }

}
